using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Jaws.Core.Web.Data;

namespace Jaws.Core.Web.Entities
{
    public class XmlCollectionBase<C, T> : Collection<T>
        where T : XmlBusinessBase<T>, new()
        where C : XmlCollectionBase<C, T>, new()
    {
        internal XmlCollectionBase(IList<T> list) : base(list) { }

        public XmlCollectionBase()
        {

        }

        public bool IsChanged
        {
            get
            {
                return ((from t in this where t.IsChanged select t).Count() > 0) ? true : false;
            }
        }

        /// <summary>
        /// Loads the specified file name.
        /// </summary>
        /// <returns></returns>
        public static C Load()
        {
            var collection = new C();

            foreach (T t in collection.GetXmlCollection())
            {
                t.MarkOld();
                collection.Add(t);
            }
            return collection;
        }

        /// <summary>
        /// Saves the specified file name.
        /// </summary>
        public void Save()
        {
            //int initialCount = Count;
            for (int i = 0; i < Count; i++)
            {
                this[i].Save();
                if (this[i].IsDeleted)
                {
                    Remove(this[i]);
                    i--;
                }
            }
        }

        public T this[Guid index]
        {
            get
            {
                return (from p in this where p.Id == index select p).First();
            }
        }

    }
}